<template>
  <el-dialog v-model="dialogVisible" title="配置" width="500" :before-close="handleClose">
    <el-form
      ref="editFormRef"
      v-loading="loading"
      style="max-width: 600px"
      :model="dataForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="平台名称" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="请输入" />
      </el-form-item>
      <el-form-item
        v-for="(item, index) in formJson"
        :key="index"
        :label="item.key == 'groupId' && item.label == 'API分组' ? 'API分组ID' : item.label"
        :prop="item.key"
        label-position="right"
      >
        <!-- mapConfig -->
        <div v-if="item.semantic === 'product'" style="width: 100%">
          <el-select
            v-model="dataForm[item.key]"
            placeholder="请选择"
            :clearable="true"
            filterable
            @change="handleSelectChange($event, item.key)"
          >
            <el-option
              v-for="(product, productKey) in mapConfig.products"
              :key="product"
              :label="productKey"
              :value="productKey"
            ></el-option>
          </el-select>
        </div>
        <div v-else-if="item.semantic === 'country'" style="width: 100%">
          <el-select
            v-if="mapConfig.iso"
            v-model="dataForm[item.key]"
            placeholder="请选择"
            :clearable="true"
            filterable
            @change="handleSelectChange($event, item.key)"
          >
            <el-option
              v-for="item in countriesList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span class="flag-icon" :class="`flag-icon-${getContryIcon(item.name)}`"></span>
              <span style="margin-left: 5px">{{ item.name }}</span>
            </el-option>
          </el-select>

          <el-select
            v-else
            v-model="dataForm[item.key]"
            placeholder="请选择"
            :clearable="true"
            filterable
            @change="handleSelectChange($event, item.key)"
          >
            <el-option
              v-for="(country, countryCode) in mapConfig.countries"
              :key="countryCode"
              :label="country.name"
              :value="countryCode"
            >
              <span class="flag-icon" :class="`flag-icon-${getContryIcon(country.name)}`"></span>
              <span style="margin-left: 5px">
                {{ country.name }}
              </span>
            </el-option>
          </el-select>
        </div>
        <div v-else style="width: 100%">
          <el-input
            v-if="['string', 'String'].includes(item.type)"
            v-model="dataForm[item.key]"
            :placeholder="item.description"
            :clearable="true"
          />
          <el-input-number
            v-if="['number', 'Number'].includes(item.type)"
            v-model="dataForm[item.key]"
            controls-position="right"
          />
          <el-switch
            v-if="['Boolean', 'boolean'].includes(item.type)"
            v-model="dataForm[item.key]"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="setDialogVisible(false)">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addConfig, editConfig, getListApi } from "@/api/platformConfig/index.api";
import useToggle from "@/hooks/useToggle";
import useCountries from "@/hooks/useCountries";

const emit = defineEmits(["refresh"]);

const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();
const { countriesList, getContryIcon } = useCountries();

const handleClose = () => {
  setDialogVisible(false);
};

const dataForm = ref({
  remark: void undefined,
});

const handleSelectChange = (value, key) => {
  dataForm.value[key] = value == undefined ? "" : value;
};

const formJson = ref({});
const rules = ref({
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const isEdist = ref(false);
const configId = ref(null);
const rowId = ref(null);
const configRows = ref({});
const handleOpen = (row, id, formRow, formId, rowCode) => {
  if (rowCode) getConfig(rowCode);

  rowId.value = formId || void undefined;
  configId.value = id || null;
  isEdist.value = false;
  if (formRow) {
    isEdist.value = true;
  }
  configRows.value = row;

  formJson.value = row.map((item) => {
    dataForm.value[item.key] = "";
    if (formRow) {
      dataForm.value[item.key] =
        formRow[item.key] || formRow[item.key] === 0 ? formRow[item.key] : null;
      dataForm.value.remark = formRow["remark"] || "";
    }
    rules.value[item.key] = [
      { required: item.required, type: item.type, message: item.description, trigger: "blur" },
    ];
    return item;
  });
  setLoading(false);
  setDialogVisible(true);
};

const mapConfig = ref({});
const getConfig = (rowCode) => {
  getListApi({
    code: rowCode,
    page: 1,
    size: 1,
  }).then((res) => {
    if (!res.rows.length) return;
    const { layout } = res.rows[0];
    mapConfig.value = {
      countries: layout.countries,
      products: layout.products,
      iso: layout.iso,
    };
  });
};

const editFormRef = ref(null);
const submitForm = async () => {
  if (!editFormRef.value) return;
  await editFormRef.value.validate((valid, fields) => {
    if (valid) {
      setLoading(true);
      const params = JSON.parse(JSON.stringify(dataForm.value));
      delete params.remark;

      let config = [];

      console.log("configRows：", configRows.value);
      for (let i = 0; i < configRows.value.length; i++) {
        const item = configRows.value[i];
        const key = item.key;
        config.push({
          key,
          value: dataForm.value[key] != undefined ? dataForm.value[key] : "",
        });
      }
      console.log("config: ", config);

      if (rowId.value)
        return editConfig({
          instanceId: rowId.value,
          thirdId: configId.value,
          remark: dataForm.value.remark,
          config,
        })
          .then(() => {
            dialogVisible.value = false;
            setLoading(false);
            emit("refresh");
            ElMessage({
              message: "配置成功",
              type: "success",
            });
          })
          .finally(() => {
            setLoading(false);
            dialogVisible.value = false;
          });

      addConfig({
        thirdId: configId.value,
        remark: dataForm.value.remark,
        config,
      })
        .then(() => {
          dialogVisible.value = false;
          setLoading(false);
          emit("refresh");
          ElMessage({
            message: "配置成功",
            type: "success",
          });
        })
        .finally(() => {
          setLoading(false);
          dialogVisible.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

defineExpose({
  handleOpen,
});
</script>
